import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar,
)
import matplotlib.pyplot as plt
import numpy as np

class PlotWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle("折线图示例")
        self.setGeometry(100, 100, 800, 600)

        # 创建主窗口的中央小部件
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        # 创建一个垂直布局
        self.layout = QVBoxLayout(self.central_widget)

        # Matplotlib 画布
        self.figure, self.ax = plt.subplots()
        self.canvas = FigureCanvas(self.figure)

        # 导航工具栏（用于放大、缩小等）
        self.toolbar = NavigationToolbar(self.canvas, self)

        # 将工具栏和画布添加到布局中
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)

        # 示例数据
        self.data = []
        for i in range(200):
            self.data.append(np.random.uniform(0, 10,1))
        self.plot()

    def plot(self):
        # 清空以前的图像
        self.ax.clear()

        # 横坐标为列表元素序号，纵坐标为列表值
        x = list(range(len(self.data)))
        y = self.data

        # 绘制折线图
        self.ax.plot(x, y, marker="o", label="示例数据")

        # 添加标题和标签
        self.ax.set_title("折线图")
        self.ax.set_xlabel("元素序号")
        self.ax.set_ylabel("值")
        self.ax.legend()

        # 刷新画布
        self.canvas.draw()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = PlotWindow()
    main_window.show()
    sys.exit(app.exec())
